package team.zero.lemon.module.workflow.service;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import team.zero.lemon.common.exception.CustomException;
import team.zero.lemon.common.persistence.Page;
import team.zero.lemon.common.security.session.SessionContext;
import team.zero.lemon.common.service.CrudService;
import team.zero.lemon.module.workflow.dao.IInstanceDao;
import team.zero.lemon.module.workflow.entity.Instance;

/**
 * Created by bolin on 2016/10/19.
 */
@Service
public class InstanceService extends CrudService<IInstanceDao, Instance> {

    @Autowired
    private WorkitemService workitemService;

    public Instance findById(Integer instanceId) {
        try {

            Instance instance = dao.findById(instanceId);
            instance.setWorkitems(workitemService.findWorkitemByInstanceId(instanceId));
            return instance;

        } catch (Exception ex) {
            throw new CustomException(ex);
        }

    }

    public Page<Instance> findMyCreateWorkflowPage(Instance instance) {
        try {
            instance.setStartUserId(SessionContext.getSession().getId());
            instance.page.setList(dao.findMyCreateWorkflowPage(instance));
            return instance.page;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    public Page<Instance> findMyInvolvedWorkflowPage(Instance instance) {
        try {
            instance.setHandleUserId(SessionContext.getSession().getId());
            instance.page.setList(dao.findMyInvolvedWorkflowPage(instance));
            return instance.page;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

    public Page<Instance> findMonitorWorkflowPage(Instance instance) {
        try {
            instance.page.setList(dao.findMonitorWorkflowPage(instance));
            return instance.page;
        } catch (Exception e) {
            throw new CustomException(e);
        }
    }

}
